// Anode-wget.h
#include <stdio.h>
#include <string.h> 
#include <stdlib.h>
#include <setjmp.h>
#include <unistd.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#ifdef NDEBUG
# define ANODE_LOG(...) return 0;
#else
# define ANODE_LOG(...) fprintf(stderr,__VA_ARGS__);
#endif
#define TRINT(EXP) jmp_buf EXP
#define TRY(EXP,JBRN) int JBRN=setjmp(EXP);if(!JBRN)
#define CATCH(JBRN,VAL) else if(JBRN==VAL)
#define THROW(EXP,VAL) (longjmp(EXP,VAL))
#define FINALLY() if(1)
#define LOCALHOST    ((const char*)"127.0.0.1")
#define DEFAULT_PORT ((unsigned)23)
#ifndef DEBUG
# define lochost LOCALHOST
# define defport DEFAULT_PORT
#endif
typedef enum {
	False,
	True,
} Bool;
typedef struct {
	unsigned    id;
	long double sign;
	const char*	server;
	char        domain[24];
	char        raw_data[1024*1024];
} raweb;
enum {
	NORMAL,
	CONNECT_FAILED=4,
	INCORRECT_IP, UNSAFE_PORT,
	PROGRAM_ABORT
} EXCEPT_VAL;
typedef struct sockaddr_in sockaddr_in;
TRINT(AnwExp);
sockaddr_in an_serv;
Bool anode_wget(raweb* web,const char* serv_ip,unsigned port) {
	int sock=socket(AF_INET,SOCK_STREAM,0);
	memset(&an_serv,0,sizeof(an_serv));
	an_serv.sin_family=AF_INET;
	an_serv.sin_addr.s_addr=inet_addr(serv_ip);
	an_serv.sin_port=htons(port);
	int a,b,c,d;
	if(sscanf(serv_ip,"%d.%d.%d.%d",&a,&b,&c,&d)<4) THROW(AnwExp,INCORRECT_IP);
	if((a<0||a>255)+(b<0||b>255)+(c<0||c>255)+(d<0||d>255)>0) THROW(AnwExp,INCORRECT_IP);
	if(port<0||port>5000) THROW(AnwExp,UNSAFE_PORT);
	int cnct=(connect(sock,(const struct sockaddr_in*)&an_serv,sizeof(an_serv)));
	if(cnct<0) {
		THROW(AnwExp,CONNECT_FAILED);
	}
	recv(sock,web,sizeof(*web),0);
	web->server=serv_ip;
	return True;
}
